闘本 2.5 リストで表された2数の和
提出
code: txt
import random
class LinkedListNode:
def __init__(self, value, next_node=None, prev_node=None):
self.value = value
self.next = next_node
self.prev = prev_node
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self, values=None):
self.head = None
self.tail = None
if values is not None:
self.add_multiple(values)
def __iter__(self):
current = self.head
while current:
yield current
current = current.next
def __str__(self):
return " -> ".join(values)
def __len__(self):
result = 0
node = self.head
while node:
result += 1
node = node.next
return result
def values(self):
def add(self, value):
if self.head is None:
self.tail = self.head = LinkedListNode(value)
else:
self.tail.next = LinkedListNode(value)
self.tail = self.tail.next
return self.tail
def add_to_beginning(self, value):
if self.head is None:
self.tail = self.head = LinkedListNode(value)
else:
self.head = LinkedListNode(value, self.head)
return self.head
def add_multiple(self, values):
for v in values:
self.add(v)
@classmethod
def generate(cls, k, min_value, max_value):
return cls(random.choices(range(min_value, max_value), k=k))
def twolistsum(ll1, ll2):
num1 = ""
for ll in ll1:
num1 += str(ll.value)
num2 = ""
for ll in ll2:
num2 += str(ll.value)
ans = int(num1 + num2)
ansll = LinkedList()
ansll.add_multiple(values)
return ansll
実行結果
code: txt
$ python -u "/Users/wafuwafu13/Deskt
op/python_playground/index.py"
7 -> 4 -> 4 -> 7
1 -> 1 -> 3
7 -> 4 -> 4 -> 7 -> 1 -> 1 -> 3